package com.tv189.springbatchtest.listener;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.listener.JobListenerFactoryBean;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

/**
 * @ClassName: StatusListenerJob
 * @Description: 任务状态监听器
 * @Author: 19202
 * @Date: 2025/5/19 22:47
 * @Version 1.0
 **/
@SpringBootApplication
@EnableBatchProcessing
public class StatusListenerJob {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Bean
    public Tasklet tasklet() {
        return new Tasklet() {
            @Override
            public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
                JobExecution jobExecution = stepContribution.getStepExecution().getJobExecution();
                System.err.println("执行中-status：" +
                        jobExecution.getStatus());

                return RepeatStatus.FINISHED;
            }
        };
    }

    @Bean
    public JobStateListener jobStateListener() {
        return new JobStateListener();
    }

    @Bean
    public Step step1() {
        return stepBuilderFactory.get("step1")
                .tasklet(tasklet())
                .build();
    }

    @Bean
    public Job job() {
        return jobBuilderFactory.get("status-anno-listen")
                .start(step1())
                .listener(JobListenerFactoryBean.getListener(new JobSateAnnoListener()))
                .build();
    }

    public static void main(String[] args) {
        SpringApplication.run(StatusListenerJob.class, args);
    }
}
